<template>
	<view class="qrcode-container">
		<u-navbar :autoBack="true" bgColor="transparent" :fixed="false"></u-navbar>
		<!-- 用户信息卡片 -->
		<!-- 		<view class="user-card">
			<view class="user-avatar">
				<image :src="myUser.HeadImg" mode="aspectFill"></image>
			</view>
			<view class="user-info">
				<view class="user-name-row">
					<text class="user-name">{{myUser.Name}}</text>
				</view>
			</view>
		</view> -->
		<view class="content-card">

			<view class="tabs">
				<view :class="['tabs-item', 'left', {'active':tabIndex == 0}]" @click="changeTab(0)">
					<view class="tabs-item-text">
						一码通
					</view>
					<image v-if="tabIndex == 0" class="active-img"
						:src="imgUrl+'upload/img/ws_static/static/ticket/tabsActive.png'" mode="widthFix">
					</image>
					<image v-if="tabIndex == 0" class="active-bg"
						:src="imgUrl+'upload/img/ws_static/static/ticket/tabsLeft.png'" mode="widthFix">
					</image>
				</view>
				<view :class="['tabs-item', 'center', {'active':tabIndex == 1}]" @click="changeTab(1)">
					<view class="tabs-item-text">
						船票
					</view>
					<image v-if="tabIndex == 1" class="active-img"
						:src="imgUrl+'upload/img/ws_static/static/ticket/tabsActive.png'" mode="widthFix">
					</image>
					<image v-if="tabIndex == 1" class="active-bg"
						:src="imgUrl+'upload/img/ws_static/static/ticket/tabsCenter.png'" mode="widthFix">
					</image>
				</view>
				<view :class="['tabs-item', 'right', {'active':tabIndex == 2}]" @click="changeTab(2)">
					<view class="tabs-item-text">
						车票
					</view>
					<image v-if="tabIndex == 2" class="active-img"
						:src="imgUrl+'upload/img/ws_static/static/ticket/tabsActive.png'" mode="widthFix">
					</image>
					<image v-if="tabIndex == 2" class="active-bg"
						:src="imgUrl+'upload/img/ws_static/static/ticket/tabsRight.png'" mode="widthFix">
					</image>
				</view>
			</view>



			<!-- 二维码卡片 -->
			<view class="qrcode-card" v-if="tabIndex ==0">
				<view class="qrcode-tip" @click="goTicket" :class="{'active': goShow}">
					{{textQrCode}}
				</view>
				<view class="qrcode-box">
					<canvas id="qrcode" canvas-id="qrcode"></canvas>
				</view>
				<view class="qrcode-refresh-tip">二维码每隔30S自动刷新</view>

				<view class="balance-row">
					<view class="balance-label">
						积分余额
						<image
							:src="showPoints ? 'https://wzws.wanshanlundiao.cn/upload/img/20250424/202504241107007611.png' : 'https://wzws.wanshanlundiao.cn/upload/img/20250424/202504241107064232.png'"
							class="toggle-points-icon" @click="togglePointsDisplay"></image>
					</view>
					<view class="balance-value">
						<image src="https://wzws.wanshanlundiao.cn/upload/img/20250421/202504211809058598.png"
							class="balance-coin" mode="widthFix"></image>
						<text>{{ showPoints ? userPoints : '******' }}</text>
					</view>
				</view>

				<!--      <view class="shop-link">支持抵扣消费门店 &gt;</view>-->
			</view>

			<!-- 船票 -->
			<view class="qrcode-card steamer" v-if="tabIndex == 1">
				<view class="order-list">
					<view class="order-item" v-for="(item,index) in steamerData" :key="index">
						<view class="item-title">
							<view class="item-title-box">
								<view class="item-title-label">
									订单号
								</view>
								<view class="item-title-value">
									{{item.OrderNo}}
								</view>
							</view>
							<view class="item-title-box">
								<view class="item-title-label">
									验证码
								</view>
								<view class="item-title-value">
									{{item.ShipOrderInfo.OrderPassword}}
								</view>
							</view>
						</view>
						<view class="item-info">
							<view class="info-title">
								<view class="info-title-left">
									<image class="order-icon"
										:src="imgUrl+'upload/img/ws_static/static/ticket/chuan.png'" mode="widthFix">
									</image>
									<view class="order-name">
										{{item.StartPortName}}-{{item.ArrivePortName}}
									</view>
								</view>
								<view class="order-price">
									￥{{item.totalAmount}}
								</view>
							</view>
							<view class="info-content">
								<view class="info-content-left">
									<view class="flight-time">
										航班时间：{{item.ClassDate}} {{item.DepartTime}}
									</view>
									<view class="passenger-name">
										{{item.PassengerNames}}
										<text class="count">共{{item.length}}张</text>
									</view>
								</view>
								<view class="checking-btn" @click="goSteamerTickets(item)">
									检票
								</view>
							</view>
						</view>
					</view>
					<view class="order-item" v-if="!steamerData || steamerData.length==0">
						<view class="noData">
							暂无数据
						</view>
					</view>
				</view>
				<view class="updata-box">
					<view class="updata-box-left" @click="getShipTicketData">
						<image class="refreshemptyIcon"
							:src="imgUrl+'upload/img/ws_static/static/ticket/refreshempty.png'" mode="widthFix"></image>
						<view class="updata-box-time">
							数据更新：{{updataTime}}
						</view>
					</view>
					<view class="updata-box-view" @click="jumpOrder">
						查看历史订单
					</view>
				</view>
				<view class="balance-row">
					<view class="balance-label">
						积分余额
						<image
							:src="showPoints ? 'https://wzws.wanshanlundiao.cn/upload/img/20250424/202504241107007611.png' : 'https://wzws.wanshanlundiao.cn/upload/img/20250424/202504241107064232.png'"
							class="toggle-points-icon" @click="togglePointsDisplay"></image>
					</view>
					<view class="balance-value">
						<image :src="imgUrl+'upload/img/ws_static/static/ticket/gold.png'" class="balance-coin"
							mode="widthFix"></image>
						<text>{{ showPoints ? userPoints : '******' }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-btn" @click="jumpPointsMall">
			<view class="shop-btn">
				<view class="shop-icon">
					<text class="icon-emoji">积</text>
				</view>
				<text class="shop-text">一键进入积分商城</text>
				<view class="btn-goto">去看看</view>
			</view>
		</view>
	</view>
</template>

<script>
	import UQRCode from "uqrcodejs"
	import HzSafeArea from "@/components/layout/hz/hz-safe-area.vue";
	import TabBar from "@/components/layout/tabbar/index.vue";
	import {
		GetUserIDQrCode,
		getUserIntegral
	} from "@/api/homePage";
	import {
		getShipTicketList
	} from "@/api/mall";
	import Config from "@/config";
	import {
		mapState
	} from 'vuex';
	import {
		formatDate
	} from '@/utils/tools.js'
	import {
		getUserShipTicketList
	} from "@/api/ws";

	export default {
		components: {
			TabBar,
			HzSafeArea
		},
		data() {
			return {
				textQrCode: '向商家或园区出示二维码进行核销',
				goShow: false,
				showPoints: false,
				userPoints: 0,
				tabIndex: 0,
				imgUrl: Config.imgUrl,
				steamerData: [],
				updataTime: '',
			}
		},
		computed: {
			...mapState({
				myUser: state => state.base.userInfo
			})
		},
		onLoad() {
			this.setUpdateTime();
			this.startIdentityCodeRefresh();
			this.getUserPoints();
			this.getShipTicketData();
		},
		beforeDestroy() {
			if (this.intervalId) clearInterval(this.intervalId)
		},
		methods: {
			jumpOrder() {
				uni.switchTab({
					url: "/pages/order/index"
				})
			},
			async getShipTicketData() {
				try {
					let date = new Date();
					// 获取前一天的日期
					date.setDate(date.getDate() - 1);
					const hours = date.getHours().toString().padStart(2, '0');
					const minutes = date.getMinutes().toString().padStart(2, '0');
					// this.updataTime = hours + ':' + minutes;
					const curDate = formatDate(date);

					// const res = await getShipTicketList({
					// 	"TicketStatus": "01,02,03,05", //
					// 	"ClassDateStart": curDate,
					// 	"ClassDateEnd": "",
					// 	"Size": 999,
					// 	"Index": 1
					// });
					const res = await getUserShipTicketList({
						"TicketStatus": "01,02,03,05", //
						"ClassDateStart": curDate,
						"ClassDateEnd": "",
						"Size": 999,
						"Index": 1
					});
					console.log("获取船票订单列表 res=>", res);
					if (res.code == 200) {
						// 统计OrderNo出现次数、收集PassengerName和总金额
						const orderNoCount = {};
						const orderNoPassengers = {};
						const orderNoTotalAmount = {};
						(res.result.Data || []).forEach(item => {
							orderNoCount[item.OrderNo] = (orderNoCount[item.OrderNo] || 0) + 1;
							if (!orderNoPassengers[item.OrderNo]) {
								orderNoPassengers[item.OrderNo] = [];
							}
							orderNoPassengers[item.OrderNo].push(item.PassengerName);
							// 累加相同订单号的总金额，避免浮点数精度问题
							const ticketPrice = parseFloat(item.TicketPrice) || 0;
							// 将金额转换为分为单位进行计算，避免浮点数精度问题
							const ticketPriceInCents = Math.round(ticketPrice * 100);
							orderNoTotalAmount[item.OrderNo] = (orderNoTotalAmount[item.OrderNo] || 0) +
								ticketPriceInCents;
						});
						// 去重并添加length、PassengerNames和totalAmount属性
						const uniqueData = [];
						const seenOrderNo = new Set();
						(res.result.Data || []).forEach(item => {
							if (!seenOrderNo.has(item.OrderNo)) {
								uniqueData.push({
									...item,
									length: orderNoCount[item.OrderNo],
									PassengerNames: orderNoPassengers[item.OrderNo].join('、'),
									totalAmount: (orderNoTotalAmount[item.OrderNo] / 100).toFixed(2)
								});
								seenOrderNo.add(item.OrderNo);
							}
						});
						// 按OrderNo降序排序
						this.steamerData = uniqueData.slice().sort((a, b) => {
							if (a.OrderNo < b.OrderNo) return 1;
							if (a.OrderNo > b.OrderNo) return -1;
							return 0;
						});
					} else {
						this.steamerData = []
						uni.showToast({
							title: res.message,
							icon: 'none'
						});
					}

				} catch (e) {
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					});
				}
			},
			goSteamerTickets(item) {
				uni.navigateTo({
					url: `/ticket_subpages/traffic/steamerTickets?OrderNo=${item.OrderNo}&source=${item.source}`
				})
			},
			changeTab(index) {
				if (index == 2) {
					uni.navigateTo({
						url: '/ticket_subpages/traffic/mpBuyTickets?isAll=true'
					})
				} else {
					this.tabIndex = index;
				}

			},
			navigateBack() {
				uni.navigateBack();
			},
			goTicket() {
				if (this.goShow) {
					uni.redirectTo({
						url: '/pages/center/index?index=2'
					})
				}
			},
			async startIdentityCodeRefresh() {
				await this.getAndDisplayQRCode();
				if (!this.intervalId) {
					this.intervalId = setInterval(async () => {
						console.log('执行定时器');
						await this.getAndDisplayQRCode();
					}, 30000);
				}
			},

			async getAndDisplayQRCode() {
				try {
					const {
						Data
					} = await GetUserIDQrCode(30);
					if (Data) {
						console.log('获取身份码++++++++++++++++++++++');
						this.loadQRCode(Data.QrCode);
					} else {
						this.$api.msg('身份码获取失败');
					}
				} catch (e) {
					console.error(e);
				}
			},

			loadQRCode(QrCode) {
				const code = Config.qrcodeUrl + 'communication?CustomerOpneid=' + QrCode;
				console.log("code ==========>", code)
				console.log(code)
				var qr = new UQRCode();
				// 设置二维码内容
				qr.data = code;
				// 设置二维码大小，必须与canvas设置的宽高一致
				qr.size = 220;
				// 调整二维码边距，避免显示不全
				qr.margin = 15;
				// 调用制作二维码方法
				qr.make();
				// 获取canvas上下文
				// 设置uQRCode实例的canvas上下文
				const ctx = uni.createCanvasContext('qrcode', this);
				// 清空画布
				ctx.clearRect(0, 0, 350, 350);
				qr.canvasContext = ctx;
				// 调用绘制方法将二维码图案绘制到canvas上
				qr.drawCanvas();
			},
			jumpPointsMall() {
				uni.navigateTo({
					url: "/mall_subpages/mall/integral"
				})
			},
			togglePointsDisplay() {
				this.showPoints = !this.showPoints;
			},
			async getUserPoints() {
				try {
					const res = await getUserIntegral();
					if (res && res.Data !== undefined) {
						this.userPoints = res.Data;
					} else {
						this.userPoints = 0;
					}
				} catch (error) {
					console.error('获取积分失败', error);
					this.userPoints = 0;
				}
			},
			setUpdateTime() {
				let date = new Date();
				const hours = date.getHours();

				// 过了凌晨12点，更新时间就是00:00；过了中午12点，更新时间就是12:00
				if (hours >= 12) {
					this.updataTime = '12:00';
				} else {
					this.updataTime = '00:00';
				}
			},
		}
	}
</script>

<style scoped lang="scss">
	.qrcode-container {
		width: 100vw;
		height: 100vh;
		background-image: url('https://wzws.wanshanlundiao.cn/upload/img/20250331/202503311833585007.jpg');
		background-repeat: no-repeat;
		background-size: cover;
		display: flex;
		flex-direction: column;
		position: relative;

		.content-card {

			width: 100%;
			padding: 60rpx 40rpx 0 40rpx;
			box-sizing: border-box;

			.tabs {
				width: 100%;
				display: flex;
				align-items: flex-end;
				background-color: #A7B1B3;
				padding-bottom: 20rpx;
				border-radius: 20rpx;

				.tabs-item {
					color: #fff;
					background-color: #A7B1B3;
					width: 33.3%;
					text-align: center;
					font-size: 30rpx;
					font-weight: 600;
					padding: 20rpx 0 30rpx 0;
					position: relative;

					&.active {
						color: #333;
						padding: 12rpx 0 0 0;
					}

					&.left {
						border-top-left-radius: 20rpx;

					}

					&.right {
						border-top-right-radius: 20rpx;
					}

					.tabs-item-text {
						position: relative;
						z-index: 1;
					}

					.active-img {
						width: 50%;
						display: inline-block;
						position: relative;
						z-index: 1;
					}

					.active-bg {
						width: 100%;
						position: absolute;
						top: -8rpx;
						left: 0;
					}
				}
			}

		}

		/* 顶部返回按钮 */
		.back-btn {
			display: flex;
			justify-content: space-between;
			padding: 80rpx 30rpx 20rpx;

			.btn-icon {
				width: 60rpx;
				height: 60rpx;
				color: #333;
				font-size: 36rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.setting-icons {
				display: flex;
				background-color: rgba(255, 255, 255, 0.8);
				border-radius: 30rpx;
				padding: 6rpx 20rpx;

				.iconfont {
					font-size: 32rpx;
					padding: 0 10rpx;
				}
			}
		}

		/* 用户信息卡片 */
		.user-card {
			padding: 20rpx 40rpx;
			margin-top: 20rpx;
			display: flex;
			align-items: center;

			.user-avatar {
				width: 130rpx;
				height: 130rpx;
				border-radius: 50%;
				overflow: hidden;
				background-color: rgba(255, 255, 255, 0.6);
				border: 1px solid rgba(255, 255, 255, 0.8);

				image {
					width: 100%;
					height: 100%;
				}
			}

			.user-info {
				margin-left: 30rpx;

				.user-name-row {
					display: flex;
					align-items: center;

					.user-name {
						font-size: 36rpx;
						font-weight: bold;
						color: #333;
					}

					.user-tag {
						margin-left: 20rpx;
						background-color: #3EC1D3;
						color: #fff;
						font-size: 20rpx;
						padding: 4rpx 16rpx;
						border-radius: 30rpx;
					}
				}

				.user-phone {
					font-size: 28rpx;
					color: #666;
					margin-top: 10rpx;
				}
			}
		}

		/* 二维码卡片 */
		.qrcode-card {
			// margin: 60rpx 40rpx 0;
			background-color: #fff;
			border-radius: 20rpx;
			padding: 40rpx 40rpx 30rpx;
			box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
			position: relative;
			margin-top: -30rpx;
			width: 100%;
			z-index: 1;
			box-sizing: border-box;

			&.steamer {
				padding: 0;

				.balance-row {
					padding: 30rpx;
					background-color: #F5FAFF;
					border-bottom-left-radius: 20rpx;
					border-bottom-right-radius: 20rpx;

					.balance-value {
						color: #FF6B0D;
					}
				}
			}

			.order-list {
				width: 100%;

				.order-item {
					border-top-left-radius: 20rpx;
					border-top-right-radius: 20rpx;
					width: 100%;
					background-color: #fff;
					// border-radius: 20rpx;
					border-bottom: 4rpx solid #F7F8FA;
					// margin-bottom: 20rpx;
					overflow: hidden;
					padding: 0 30rpx;
					box-sizing: border-box;

					.noData {
						width: 100%;
						height: 200rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						color: #999;
					}

					.item-title {
						width: 100%;
						display: flex;
						justify-content: space-between;
						align-items: center;

						// background-color: #ECF5F9;
						color: #666;

						.item-title-box {
							display: flex;
							align-items: center;
							border-bottom: 2rpx solid #F7F8FA;
							padding: 30rpx 0;

							.item-title-label {

								margin-right: 10rpx;
							}

							.item-title-value {
								font-size: 28rpx;
								color: #90949C;
							}
						}
					}

					.item-info {
						padding: 30rpx 0;

						.info-title {
							display: flex;
							justify-content: space-between;
							align-items: center;
							margin-bottom: 20rpx;
							width: 100%;

							.info-title-left {
								display: flex;
								align-items: center;
								width: 65%;

								.order-icon {
									width: 40rpx;
									height: 40rpx;
									margin-right: 20rpx;
								}

								.order-name {
									font-size: 32rpx;
									font-weight: bold;
									color: #333;
								}
							}

							.order-price {
								font-size: 32rpx;
								font-weight: bold;
								color: #333;
								text-align: right;
								width: 35%;
							}
						}

						.info-content {
							display: flex;
							justify-content: space-between;
							align-items: flex-end;
							padding-left: 60rpx;

							.info-content-left {
								font-size: 26rpx;
								color: #90949C;

								.count {
									margin-left: 20rpx;
									color: #00ACF4;
								}

								.flight-time {
									margin-bottom: 10rpx;
								}
							}

							.checking-btn {
								padding: 8rpx 30rpx;
								border-radius: 30rpx;
								font-size: 28rpx;
								margin-left: 20rpx;
								border: 2rpx solid #00ACF4;
								color: #00ACF4;
							}
						}
					}
				}
			}

			.updata-box {
				width: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx;

				.updata-box-left {
					display: flex;
					align-items: center;
					width: 60%;
					font-size: 26rpx;
					color: #C2C4C9;

					.refreshemptyIcon {
						width: 60rpx;
					}

					.updata-box-time {
						padding-left: 20rpx;
					}
				}

				.updata-box-view {
					color: #37BDF5
				}
			}


			.qrcode-tip {
				text-align: center;
				font-size: 30rpx;
				color: #333;
				margin-bottom: 25rpx;

				&.active {
					color: #498FFF;
				}
			}

			.qrcode-box {
				width: 500rpx;
				height: 500rpx;
				margin: 0 auto;
				background-color: #fff;
				display: flex;
				justify-content: center;
				align-items: center;

				canvas {
					width: 220px;
					height: 220px;
				}
			}

			.qrcode-refresh-tip {
				text-align: center;
				font-size: 22rpx;
				color: #999;
				margin-top: 15rpx;
				margin-bottom: 30rpx;
			}

			.balance-row {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;
				border-top: 1px solid #f5f5f5;
				padding-top: 20rpx;


				.balance-label {
					font-size: 28rpx;
					color: #666;
					display: flex;
					align-items: center;

					.toggle-points-icon {
						width: 40rpx;
						height: 40rpx;
						margin-left: 10rpx;
						cursor: pointer;
					}
				}

				.balance-value {
					font-size: 28rpx;
					color: #498FFF;
					font-weight: bold;
					display: flex;
					align-items: center;

					.balance-coin {
						margin-right: 12rpx;
						width: 30rpx;
						// height: 30rpx;
					}
				}
			}

			.shop-link {
				text-align: center;
				font-size: 26rpx;
				color: #498FFF;
				margin-top: 20rpx;
			}
		}

		/* 底部按钮 */
		.bottom-btn {
			margin-top: auto;
			padding: 40rpx;
			margin-bottom: 60rpx;

			.shop-btn {
				background-color: #FFE4BD;
				border-radius: 50rpx;
				padding: 30rpx;
				display: flex;
				align-items: center;
				position: relative;

				.shop-icon {
					width: 60rpx;
					height: 60rpx;
					color: #F39800;
					display: flex;
					align-items: center;
					justify-content: center;

					.icon-emoji {
						font-size: 36rpx;
					}
				}

				.shop-text {
					font-size: 30rpx;
					color: #333;
					margin-left: 20rpx;
				}

				.btn-goto {
					position: absolute;
					right: 30rpx;
					background-color: #fff;
					color: #333;
					padding: 6rpx 24rpx;
					border-radius: 30rpx;
					font-size: 22rpx;
				}
			}
		}
	}
</style>